<?php

namespace Home\Controller;
use Think\Controller;

class CommonController extends Controller {

    protected $wechat;
    public function _initialize() {
         vendor ( 'Wechat.Wechat' );
         $this->wechat = new \Wechat(
             array(
                 'appid' => 'wx4a48e9196b72de1d',
                 'appsecret'=> '1ba17062e0e4bf933d6397b0eef19324'
                 )
             );
        !session('user_id') && $this->auth();
        !IS_POST &&  $signPackage = $this->wechat->getJsSign("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        $user = D('User')->where(array('id'=>session('user_id')))->find();
        
        session('user',$user);
        $this->assign('signPackage',$signPackage);
        $this->assign('user',$user);
    }

    public function auth() {
        
         if($oauth_access_token = $this->wechat->getOauthAccessToken()) {
             $oauth_user_info = $this->wechat->getOauthUserinfo($oauth_access_token['access_token'], $oauth_access_token ['openid'] );
            
             if(!$user = D('User')->where(array('openid'=>$oauth_access_token['openid'] ))->find ()) {
                $users = D ( 'User' )->add ( $oauth_user_info );
               session('user_id',$users);
            }else{
                 session('user_id',$user['id']);
             }
            
            exit(header( 'Location: ' . U('',null,true,true )));
       } else {
            exit(header('Location: ' . $this->wechat->getOauthRedirect (U('',null,true,true))));
        }
    }
}